import React, { useState } from 'react';
import { 
  Layout, Menu, Button, Dropdown, Avatar, 
  Typography, Breadcrumb, Modal, message 
} from 'antd';
import { 
  UserOutlined, LogoutOutlined, UploadOutlined,
  HomeOutlined, LineChartOutlined, FundOutlined,
  BranchesOutlined, ApartmentOutlined,
  MenuUnfoldOutlined, MenuFoldOutlined
} from '@ant-design/icons';
import { Routes, Route, Link, useNavigate, useLocation } from 'react-router-dom';

// 导入页面组件
import Home from './Home';
import DataUpload from './DataUpload';
import ICAAnalysis from './analysis/ICAAnalysis';
import AEAnalysis from './analysis/AEAnalysis';
import PCAAnalysis from './analysis/PCAAnalysis';
import PLSAnalysis from './analysis/PLSAnalysis';
import NotFound from './NotFound';

const { Header, Sider, Content } = Layout;
const { Title } = Typography;

const Dashboard = ({ user, onLogout }) => {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  
  // 获取当前路径的key
  const getSelectedKey = () => {
    const path = location.pathname;
    if (path === '/') return '1';
    if (path === '/upload') return '2';
    if (path.startsWith('/ica')) return '3';
    if (path.startsWith('/ae')) return '4';
    if (path.startsWith('/pca')) return '5';
    if (path.startsWith('/pls')) return '6';
    return '1';
  };
  
  // 处理退出登录
  const handleLogout = () => {
    Modal.confirm({
      title: '确认退出登录?',
      content: '您确定要退出登录吗?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        message.success('已退出登录');
        onLogout();
      }
    });
  };
  
  // 用户菜单
  const userMenu = (
    <Menu>
      <Menu.Item key="profile" icon={<UserOutlined />}>
        个人信息
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );
  
  // 面包屑映射
  const breadcrumbMap = {
    '/': ['首页'],
    '/upload': ['首页', '数据上传'],
    '/ica': ['首页', 'ICA分析'],
    '/ae': ['首页', 'AE分析'],
    '/pca': ['首页', 'PCA分析'],
    '/pls': ['首页', 'PLS分析']
  };
  
  // 获取面包屑项
  const getBreadcrumbItems = () => {
    const pathSnippets = location.pathname.split('/').filter(i => i);
    const items = ['首页'];
    
    pathSnippets.forEach((path, index) => {
      const pathKey = pathSnippets.slice(0, index + 1).join('/');
      let item = '';
      
      switch(path) {
        case 'ica':
          item = 'ICA分析';
          break;
        case 'ae':
          item = 'AE分析';
          break;
        case 'pca':
          item = 'PCA分析';
          break;
        case 'pls':
          item = 'PLS分析';
          break;
        case 'upload':
          item = '数据上传';
          break;
        default:
          item = path;
      }
      
      if (item) items.push(item);
    });
    
    return items;
  };
  
  return (
    <Layout>
      <Sider 
        trigger={null} 
        collapsible 
        collapsed={collapsed}
        width={220}
        style={{
          overflow: 'auto',
          height: '100vh',
          position: 'fixed',
          left: 0,
          top: 0,
          bottom: 0
        }}
      >
        <div className="logo">
          {!collapsed ? '华泰智能诊断系统' : '华泰'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={[getSelectedKey()]}
          selectedKeys={[getSelectedKey()]}
        >
          <Menu.Item key="1" icon={<HomeOutlined />}>
            <Link to="/">首页</Link>
          </Menu.Item>
          <Menu.Item key="2" icon={<UploadOutlined />}>
            <Link to="/upload">数据上传</Link>
          </Menu.Item>
          <Menu.Item key="3" icon={<BranchesOutlined />}>
            <Link to="/ica">独立成分分析(ICA)</Link>
          </Menu.Item>
          <Menu.Item key="4" icon={<ApartmentOutlined />}>
            <Link to="/ae">自动编码器(AE)</Link>
          </Menu.Item>
          <Menu.Item key="5" icon={<LineChartOutlined />}>
            <Link to="/pca">主成分分析(PCA)</Link>
          </Menu.Item>
          <Menu.Item key="6" icon={<FundOutlined />}>
            <Link to="/pls">偏最小二乘分析(PLS)</Link>
          </Menu.Item>
        </Menu>
      </Sider>
      
      <Layout style={{ marginLeft: collapsed ? 80 : 220, transition: 'all 0.2s' }}>
        <Header 
          style={{ 
            background: '#fff', 
            padding: '0 16px', 
            display: 'flex', 
            alignItems: 'center',
            justifyContent: 'space-between',
            boxShadow: '0 1px 4px rgba(0, 21, 41, 0.08)'
          }}
        >
          <Button 
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            size="large"
          />
          
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Dropdown overlay={userMenu} placement="bottomRight">
              <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
                <Avatar icon={<UserOutlined />} />
                <span style={{ marginLeft: '8px' }}>{user?.username || 'Admin'}</span>
              </div>
            </Dropdown>
          </div>
        </Header>
        
        <Content style={{ margin: '16px', overflow: 'initial' }}>
          <div className="site-layout-background content-container">
            <Breadcrumb style={{ marginBottom: '16px' }}>
              {getBreadcrumbItems().map((item, index) => (
                <Breadcrumb.Item key={index}>{item}</Breadcrumb.Item>
              ))}
            </Breadcrumb>
            
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/upload" element={<DataUpload />} />
              <Route path="/ica/*" element={<ICAAnalysis />} />
              <Route path="/ae/*" element={<AEAnalysis />} />
              <Route path="/pca/*" element={<PCAAnalysis />} />
              <Route path="/pls/*" element={<PLSAnalysis />} />
              <Route path="*" element={<NotFound />} />
            </Routes>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default Dashboard; 